# build a CPack driven installer package
include(InstallRequiredSystemLibraries)

set(EXE_NAME DLUTFEM)

set(CPACK_PACKAGE_NAME ${EXE_NAME})
set(CPACK_PACKAGE_VENDOR "DLUT")
set(CPACK_PACKAGE_VERSION ${CMAKE_PROJECT_VERSION})
set(CPACK_PACKAGE_DESCRIPTION_SUMMARY ${CMAKE_PROJECT_DESCRIPTION})
set(CPACK_PACKAGE_HOMEPAGE_URL ${CMAKE_PROJECT_HOMEPAGE_URL})
set(CPACK_RESOURCE_FILE_LICENSE "${CMAKE_SOURCE_DIR}/LICENSE")
set(CPACK_RESOURCE_FILE_README "${CMAKE_SOURCE_DIR}/README.md")


# NSIS Windows installer
IF(MINGW)
    set(CPACK_GENERATOR "NSIS")
    set(CPACK_SET_DESTDIR OFF)

    set(CPACK_NSIS_MUI_ICON "${CMAKE_SOURCE_DIR}/Resource/img/logo.ico")
    SET(CPACK_NSIS_INSTALLED_ICON_NAME "\\\\bin\\\\${EXE_NAME}.exe")
    SET(CPACK_NSIS_DISPLAY_NAME "${CPACK_PACKAGE_INSTALL_DIRECTORY}${EXE_NAME}")
    SET(CPACK_NSIS_HELP_LINK ${CPACK_PACKAGE_HOMEPAGE_URL})
    SET(CPACK_NSIS_CONTACT ${CMAKE_PROJECT_HOMEPAGE_URL})
    SET(CPACK_NSIS_MODIFY_PATH ON)
    SET(CPACK_NSIS_ENABLE_UNINSTALL_BEFORE_INSTALL ON)
    set(CMAKE_WINDOWS_EXPORT_ALL_SYMBOLS TRUE)
    set(CPACK_PACKAGE_INSTALL_DIRECTORY "${EXE_NAME}")
    set(CPACK_PACKAGE_FILE_NAME "${EXE_NAME}-${PROJECT_VERSION}")
    # 查找 Git 可执行文件
    find_package(Git QUIET)

    if(GIT_FOUND)
        # 获取短格式的最新 commit hash (例如: a1b2c3d)
        execute_process(
            COMMAND ${GIT_EXECUTABLE} rev-parse --short HEAD
            WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}
            OUTPUT_VARIABLE GIT_COMMIT_HASH
            OUTPUT_STRIP_TRAILING_WHITESPACE
            ERROR_QUIET # 静默错误（比如非 git 目录）
        )
        set(CPACK_PACKAGE_FILE_NAME "${CPACK_PACKAGE_FILE_NAME}-${GIT_COMMIT_HASH}")
    else()
        set(GIT_COMMIT_HASH "unknown")
        message(WARNING "Git not found. Commit hash will be 'unknown'.")
    endif()

    set(CPACK_PRE_BUILD_SCRIPTS "${CMAKE_SOURCE_DIR}/Resource/cmake/CPackPreBuild.cmake")

    set(CPACK_NSIS_CREATE_ICONS_EXTRA "
        CreateShortCut '\\$SMPROGRAMS\\\\$STARTMENU_FOLDER\\\\${EXE_NAME}.lnk' '\\$INSTDIR\\\\bin\\\\${EXE_NAME}.exe'
        CreateShortCut '\\$DESKTOP\\\\${EXE_NAME}.lnk' '\\$INSTDIR\\\\bin\\\\${EXE_NAME}.exe'
        ")
    set(CPACK_NSIS_DELETE_ICONS_EXTRA "
        Delete '\\$SMPROGRAMS\\\\$STARTMENU_FOLDER\\\\${EXE_NAME}.lnk'
        Delete '\\$DESKTOP\\\\${EXE_NAME}.lnk'
        ")

else()
    set(CPACK_GENERATOR "ZIP")
endif()


# 打包 
include(CPack)
